package com.iot.comprehensive.face.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @Author 朱泽玉
 * @Create 2021/6/26 12:52
 * @Description
 * @Modified By:
 */
@Data
@ConfigurationProperties("jwt.config")
public class Jwt {
    // 私钥
    private String key;
    // 失效时间
    private Long ttl;
//    // 用户名
//    private String mobile;
//    // 密码
//    private String password;

    public String create(String id, Map<String, Object> map){
        Long now =System.currentTimeMillis();//当前毫秒数
        //设置失效时间
        long exp = now +ttl;
        JwtBuilder builder = Jwts.builder();
        builder.setClaims(map);
        builder.setId(id)
                .setIssuedAt(new Date())//设置时间
                .signWith(SignatureAlgorithm.HS256,key)//签名私钥
                .setExpiration(new Date(exp));//失效时间
        //创建token
        return builder.compact();
    }

    public Claims parse(String token){
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    }

    public Claims token(HttpServletRequest request){
        //1、获取token
        String token = request.getHeader("Authorization");
        //2、查看token是否位空
        if (token == null || token.isEmpty()) {
            return null;
        }
        // 3、解析token
        return this.parse(token);
    }
}
